<template>
  <div class="order-detail-container">
    <div class="order-detail-card">
      <h3>订单详情</h3>
      <el-card>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单号">{{ order.id }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ order.course }}</el-descriptions-item>
          <el-descriptions-item label="价格">{{ order.price }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(order.status)">{{ order.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ order.date }}</el-descriptions-item>
        </el-descriptions>
        <div class="action-buttons">
          <el-button type="primary" @click="goToOrderList">返回订单列表</el-button>
          <el-button 
            v-if="order.status === '待支付'" 
            type="success" 
            @click="continuePayment">
            继续支付
          </el-button>
          <el-button 
            v-if="order.status === '已完成'" 
            type="success" 
            @click="studyCourse">
            立即学习
          </el-button>
          <el-button 
            v-if="order.status === '待支付' && withinTwoHours" 
            type="warning" 
            @click="cancelOrder">
            取消订单(2小时内)
          </el-button>
          <el-button 
            v-if="order.status !== '待支付'" 
            type="danger" 
            @click="deleteOrder">
            删除订单
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OrderDetail',
  data() {
    return {
      order: {
        id: this.$route.params.id,
        course: '',
        price: '',
        status: '',
        date: ''
      },
      orderTime: new Date() // 添加订单创建时间记录
    }
  },
  created() {
    // 从Vuex store获取订单详情
    const foundOrder = this.$store.state.orders.find(order => order.id === this.$route.params.id);
    if (foundOrder) {
      this.order = foundOrder;
      this.orderTime = new Date(foundOrder.date);
    } else {
      // 如果没有在store中找到，使用模拟数据
      const mockOrders = [
        {
          id: '20230001',
          course: 'Vue.js入门课程',
          price: '¥199',
          status: '已完成',
          date: '2023-01-15'
        },
        {
          id: '20230002',
          course: 'Element UI实战',
          price: '¥299',
          status: '待支付',
          date: '2023-01-16'
        }
      ];
      
      const mockOrder = mockOrders.find(order => order.id === this.$route.params.id);
      if (mockOrder) {
        this.order = mockOrder;
        this.orderTime = new Date(mockOrder.date);
      }
    }
  },
  computed: {
    // 计算是否在2小时内
    withinTwoHours() {
      const now = new Date();
      const diffInHours = (now - this.orderTime) / (1000 * 60 * 60);
      return diffInHours <= 2;
    }
  },
  methods: {
    getStatusTagType(status) {
      const map = {
        '待支付': 'warning',
        '已完成': 'success',
        '已取消': 'danger'
      };
      return map[status] || '';
    },
    goToOrderList() {
      this.$router.push('/dashboard/orders');
    },
    continuePayment() {
      this.$router.push(`/dashboard/payment/${this.order.id}`);
    },
    studyCourse() {
      // 从课程名称中提取课程ID
      const courseMatch = /(\d+)/.exec(this.order.course);
      if (courseMatch) {
        const courseId = parseInt(courseMatch[1]);
        // 添加到已购买课程列表，确保能通过CourseStudy组件的判断
        if (!this.$store.getters.isCourseAlreadyPurchased(courseId)) {
          this.$store.dispatch('addPurchasedCourse', {
            id: courseId,
            name: this.order.course,
            purchaseDate: this.order.date
          });
        }
        // 跳转到课程学习页面
        this.$router.push(`/dashboard/study/${courseId}`);
      } else {
        // 如果无法识别课程ID，尝试使用课程名称匹配
        if (this.order.course.includes('Vue.js入门')) {
          const courseId = 1;
          if (!this.$store.getters.isCourseAlreadyPurchased(courseId)) {
            this.$store.dispatch('addPurchasedCourse', {
              id: courseId,
              name: this.order.course,
              purchaseDate: this.order.date
            });
          }
          this.$router.push(`/dashboard/study/${courseId}`);
        } else if (this.order.course.includes('Element UI')) {
          const courseId = 2;
          if (!this.$store.getters.isCourseAlreadyPurchased(courseId)) {
            this.$store.dispatch('addPurchasedCourse', {
              id: courseId,
              name: this.order.course,
              purchaseDate: this.order.date
            });
          }
          this.$router.push(`/dashboard/study/${courseId}`);
        } else {
          this.$message.warning('无法识别课程ID，请联系客服');
        }
      }
    },
    cancelOrder() {
      this.$confirm('确定要取消订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 更新订单状态
        this.$store.dispatch('updateOrderStatus', {
          id: this.order.id,
          status: '已取消'
        });
        this.$message.success('订单已取消');
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
    deleteOrder() {
      this.$confirm('确定要删除订单吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除订单
        this.$store.dispatch('deleteOrder', this.order.id);
        this.$message.success('订单已删除');
        this.goToOrderList();
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }
}
</script>

<style scoped>
.order-detail-container {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.order-detail-card {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.order-detail-card h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 20px;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
}

.action-buttons .el-button {
  margin-left: 0;
  margin-right: 0;
  margin-bottom: 5px;
}

@media screen and (max-width: 768px) {
  .action-buttons {
    flex-direction: column;
    align-items: center;
  }
  
  .action-buttons .el-button {
    width: 100%;
    max-width: 200px;
  }
}
</style>